package cn.edu.nju.software.androidsymplayer;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class BaiduMusicHandler extends DefaultHandler {
	private String musicURL;
	private boolean in_url = false;
	private boolean in_encode = false;
	private boolean in_decode = false;
	private int count = 0;

	public String getMusicURL() {
		return this.musicURL;
	}

	@Override
	public void startDocument() throws SAXException {

	}

	@Override
	public void endDocument() throws SAXException {

	}

	@Override
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		if (localName.equals("url"))
			this.in_url = true;
		else if (localName.equals("encode")) {
			this.in_encode = true;
			this.count++;
		} else if (localName.equals("decode"))
			this.in_decode = true;
	}

	@Override
	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (localName.equals("url"))
			this.in_url = false;
		else if (localName.equals("encode"))
			this.in_encode = false;
		else if (localName.equals("decode"))
			this.in_decode = false;
	}

	@Override
	public void characters(char ch[], int start, int length) {
		if (this.in_encode && this.count == 1) {
			String url = new String(ch, start, length);
			if (url.endsWith(".mp3"))
				musicURL = url;
			else
				this.count--;
		} else if (this.in_decode && this.count == 1) {
			String str = new String(ch, start, length);
			String[] UrlSplit = musicURL.split("/");
			musicURL = musicURL.replace(UrlSplit[UrlSplit.length - 1], str);
		}
	}
}
